<template>
  <div>
    <BreakSpace label="出卖人信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel
      ref="sellerInfo"
      :list="initFormSeller"
      :cols="3"
      :labelWidth="140"
      :isSubmitBtn="false"
      :formType="infoBasic"
      @formChange="formChangeHandleSeller"
    />
    <BreakSpace label="买受人信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel
      ref="buyerInfo"
      :list="initFormBuyer"
      :cols="3"
      :labelWidth="140"
      :isSubmitBtn="false"
      :formType="infoBasic"
      @formChange="formChangeHandleBuyer"
    />
    <BreakSpace label="合同信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel
      ref="contractInfo"
      :list="initFormContract"
      :cols="3"
      :labelWidth="140"
      :isSubmitBtn="false"
      :formType="infoBasic"
      @formChange="formChangeHandleContract"
    />
    <BreakSpace label="附件信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel
      ref="fileInfo"
      :list="initFormFile"
      :cols="1"
      :labelWidth="140"
      :isSubmitBtn="false"
      :formType="infoBasic"
      @formChange="formChangeHandleFile"
    />
    <!-- table -->
    <BreakSpace label="车辆信息" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      height='300'
      ref="table"
      :columns="columns"
      :dataSource="dataSource"
      :isColumnFilter="false"
      :isSelectColumn="isSelectColumn"
      :datakey="'dealerName'"
      :isToperInfo="false"
      columnsRef='customerManage_filingManage_contractFiling_addDialog_01'
      :onColumnsChange="columns => this.columns = columns"
    >
      <!-- <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="productHandle">选择车辆</el-button>
      </template> -->
    </FilterTable>
    <div class="dialogBottmView" >
      <el-button @click="closeDialog">取 消</el-button>
      <el-button @click="saveDialog" v-if="infoBasic != 'show'" type="primary">{{ btnText }}</el-button>
    </div>
    <!-- 项目信息弹窗 -->
    <BaseDialog 
      title="项目选择" 
      width="1000px"
      destroyOnClose
      :visible.sync="visibleProject"
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}" >
      <project-madal  ref="projectDialog" @close="closeProject" />
   </BaseDialog>
    <!-- 车辆信息弹窗 -->
    <BaseDialog 
      title="车辆选择" 
      width="700px"
      destroyOnClose
      :visible.sync="visibleProduct"
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}" >
      <product-madal  ref="productDialog" @close="closeProduct" />
   </BaseDialog>
   <!-- 经销商弹窗 -->
    <BaseDialog
      title="经销商查询"
      :visible.sync="visibleDealer"
      width="1000px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <dealer-madal  ref='addDialogRef' selectType='single' v-model="initDealerData"  @close="closeDealer" />
    </BaseDialog>
  </div>
</template>
<script>
// import personnelMadal from '@/pages/cms-common/user'
import {parseTime, formatdateByDay } from '@/utils/index';
import projectMadal from '@/pages/cms-pages/customerManage/approvalManage/inquire/contractRegisterSelectList'
import productMadal from '@/pages/cms-common/product'
import dealerMadal from '@/pages/cms-common/dealerdata'
import { dictionary } from '@/utils/dictMixin';
import { insertContract ,updataContract ,searchDetailListByContractId  } from '@/api/cms-api/customerManage/filingManage/contractRegister';
export default {
  components: {
    projectMadal,dealerMadal,productMadal
  },
  props: {
    value:{
        type: Object,
        default: null
    }
  },
  mixins: [dictionary],
  data() {
    this.conf = { add: '保 存', edit: '修 改' };
    return {
      contractId:"",
      editRow:{},
      formData:[],
      dealerList:[],
      productList:[],
      visibleProject: false,
      visibleProduct: false,
      visibleDealer: false,
      initDealerData:{},
      dataSource:[],
      isSelectColumn: false,
      infoBasic:this.value.type,
      initFormSeller: this.initFormSellerFun(),
      initFormBuyer: this.initFormBuyerFun(),
      initFormContract: this.initFormContractFun(),
      initFormFile: this.initFormFileFun(),
      columns: this.creatHeader()
    };
  },
  mounted() {
    //如果传入参数不为空，则说明是修改进入，初始化对应数据
    if(this.value!=null && (this.value.type=="edit"||this.value.type=="show")){
      this.init();
    }
    
  },
  computed: {
    //根据传入参数，确定底部按钮名称
    btnText() {
      return this.conf[this.value.type];
    }
  },
  methods: {
    //修改时，初始化页面数据
    async init(){
      // 更新接口需要的记录 ID
      this.contractId = this.value.rowData.contractId;
      //循环为表单赋值
      this.initFormSeller.forEach(x => {
        x.initialValue = this.value.rowData[x.fieldName];
      });
      this.initFormBuyer.forEach(x => {
        x.initialValue = this.value.rowData[x.fieldName];
      });
      this.initFormContract.forEach(x => {
        if(x.fieldName=="contractPrice"){
          x.initialValue = parseFloat(this.value.rowData[x.fieldName]);
        }else if(x.fieldName=="contractStartDate"){ //合同生效日期

         x.initialValue =  formatdateByDay(new Date(this.value.rowData[x.fieldName]));
        }else if(x.fieldName=="totalNum"){
          x.initialValue = this.value.rowData[x.fieldName];
        }else{
          x.initialValue = this.value.rowData[x.fieldName];
        }
      });
      //附件信息回显
      this.initFormFile.forEach(x => {
        let urlsList = this.value.rowData.urls;
        if(urlsList!=null && urlsList.length>0){
          let fileList = [];
          for(let i in urlsList){
              let fileName = { name: urlsList[i].fileName };
              let fileId = { url: urlsList[i].fileId };
              let f = Object.assign(fileName, fileId);
              fileList.push(f);
          }
          //x.initialValue = Object.assign({}, { fileUrl: fileList });
          x.initialValue = fileList;
        }
      });

      //回显车辆信息
      let res = await searchDetailListByContractId(Object.assign({},{contractId : this.contractId}));
     if (res.resultCode === 200) {
        for(let i in res.data){
            this.productList.push(res.data[i].materialId);
            this.dataSource.push(Object.assign({},res.data[i]));
        }

      }else {
        this.$notify.error({title: '提示信息',message:'获取车辆信息失败!'});
      }
    },
    //出卖人信息数据
    initFormSellerFun() {
      return [
         {
          type: 'INPUT',
          label: '出卖人（甲方）',
          fieldName: 'sellerName',
          placeholder: '请输入',
          initialValue: '',
          
        },
        {
          type: 'INPUT',
          label: '住所',
          fieldName: 'sellerAddress',
          placeholder: '请输入',
          selfCols:2,
          initialValue: '',
          
        },
        {
          type: 'INPUT',
          label: '授权代表人',
          fieldName: 'sellerAuthorizer',
          placeholder: '请输入',
          initialValue: '',
          
        },{
          type: 'INPUT',
          label: '联系人',
          fieldName: 'sellerContact',
          placeholder: '请输入',
          initialValue: '',
          
        },
        {
          type: 'INPUT',
          label: '联系方式',
          fieldName: 'sellerMobile',
          placeholder: '请输入',
          initialValue: '',
          
        },
        {
          type: 'INPUT',
          label: '工作邮箱',
          fieldName: 'sellerEmail',
          placeholder: '请输入',
          initialValue: '',
          
        }
      ];
    },
    //买受人信息数据
    initFormBuyerFun() {
      return [
         {
          type: 'INPUT',
          label: '买受人（乙方）',
          fieldName: 'buyerName',
          placeholder: '请输入',
          // disabled: true,
          initialValue: '',
          
        },
        {
          type: 'INPUT',
          label: '地址',
          fieldName: 'buyerAddress',
          placeholder: '请输入',
          selfCols:2,
          initialValue: '',
          
        },
        {
          type: 'INPUT',
          label: '授权代表人',
          fieldName: 'buyerAuthorizer',
          placeholder: '请输入',
          initialValue: '',
          
        },{
          type: 'INPUT',
          label: '联系人',
          fieldName: 'buyerContact',
          placeholder: '请输入',
          initialValue: '',
          
        },
        {
          type: 'INPUT',
          label: '联系方式',
          fieldName: 'buyerMobile',
          placeholder: '请输入',
          initialValue: '',
          
        },
        {
          type: 'INPUT',
          label: '工作邮箱',
          fieldName: 'buyerEmail',
          placeholder: '请输入',
          initialValue: '',
          
        },
        {
          type: 'INPUT',
          label: '项目名称',
          fieldName: 'projectName',
          placeholder: '请输入',
          initialValue: '',
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={() => this.projectHandle()}></el-button>;
          },
          
        }
      ];
    },
    //合同信息数据
    initFormContractFun() {
      return [
         {
          type: 'INPUT',
          label: '合同名称',
          fieldName: 'contractName',
          placeholder: '请输入',
          initialValue: '',
          
        },
        {
          type: 'INPUT',
          label: '合同编号',
          fieldName: 'contractNum',
          placeholder: '请输入',
          initialValue: '',
          
        },
        {
          type: 'SELECT',
          label: '资金类型',
          fieldName: 'accoutType',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictList('2569'),
          
        },
        {
          type: 'DATE',
          label: '合同生效日期',
          fieldName: 'contractStartDate',
          style: { width: '100%' },
          initialValue: '',
          readonly : true,
          
        },
        {
          type: 'SELECT',
          label: '交车类型',
          fieldName: 'transportType',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictList('2525'),
          
        },
        {
          // type: 'INPUT_NUMBER',
          type: 'INPUT',
          label: '合同金额（含税）',
          fieldName: 'contractPrice',
          placeholder: '请输入',
          initialValue: 0,
          precision:2,
          numberFormat:true,
          max:99999999,
          
        },
        {
          type: 'INPUT_NUMBER',
          label: '订购总数量',
          fieldName: 'totalNum',
          initialValue: 0,
          placeholder: '请输入',
          
        },
        {
          type: 'SELECT',
          label: '是否赠送充电桩',
          fieldName: 'isCharge',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictList('1004'),
          
        },
        {
          type: 'INPUT',
          label: '收车地址',
          fieldName: 'receiveAddress',
          placeholder: '请输入',
          selfCols:2,
          initialValue: '',
          
        },
        {
          type: 'TEXT_AREA',
          label: '特殊约定',
          fieldName: 'specialAgree',
          placeholder: '请输入',
          selfCols:3,
          initialValue: ''
        }
      ];
    },
    //附件信息数据
    initFormFileFun() {
      return [
        {
          type: 'UPLOAD_FILE',
          label: '附件',
          disabled: this.type === 'show' ? true : false,
          fieldName: 'fileUrl',
          initialValue: '',
          upload: {
            actionUrl: '/api/file/oss/upload'
          }
        }
      ];
    },

    
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
       
        { title: '交车经销商', dataIndex: 'dealerName', sorter: true,
          // render: props => { return <el-input placeholder="请输入内容" value={props.row.dealerName} ><el-button onClick={() => this.dealerHandle(props.row)}  slot="append" icon="el-icon-search" ></el-button></el-input>;}
        },
        { title: '品牌', dataIndex: 'brandName', sorter: true },
        { title: '车系', dataIndex: 'seriesName', sorter: true },
        { title: '车型', dataIndex: 'modelName', sorter: true },
        { title: '配置', dataIndex: 'packageName', sorter: true },
        { title: '内饰', dataIndex: 'trimColor', sorter: true },
        { title: '颜色', dataIndex: 'color', sorter: true },
        { title: '整车编码', dataIndex: 'productCode', sorter: true },
        { title: '商品名称', dataIndex: 'productName', sorter: true },
        { title: '生产厂商', dataIndex: 'manufacturer', sorter: true },
        { title: '产地', dataIndex: 'originPlace', sorter: true },
        { title: '数量', dataIndex: 'contractNum', sorter: true },
        { title: '出厂单价', dataIndex: 'factorySinglePrice',  sorter: true  },
        { title: '国家补贴', dataIndex: 'stateSubsidy', sorter: true  },
        { title: '地方补贴', dataIndex: 'localSubsidy', sorter: true  },
        { title: '商务政策折让', dataIndex: 'discount', sorter: true  },
        { title: '扣除补贴/价格折让后单价', dataIndex: 'actualSinglePrice', sorter: true },
        { title: '扣除补贴/价格折让后总价', dataIndex: 'actualTotalPrice', sorter: true ,numberFormat:true, }
      ];
    },
     // 项目信息 打开窗口
    proectHandle() {
      this.visibleProect = true;
    },
    // 项目信息 关闭窗口 -返回数据
    closeProject(data) {
      // this.dataSource = data.data;
      // this.dataSource=[
      //   {id:'1111',field0:'吉林公司',field1:'DS2345768',field2:'吉林',field3:'A',field6:'吉林省',field7:'长春市',field8:'南关区'}
      // ]
      //返回数据逻辑自己写
      this.visibleProject = data.visible; //关闭弹窗
    },
    // 车辆信息 打开窗口
    productHandle() {
      this.visibleProduct = true;
    },
    // 车辆信息 关闭窗口 -返回数据
    closeProduct(data) {

      if(data.data&&data.data.length){
        let haveId = false;
        for(let i in this.productList){
           if(this.productList[i]==data.data[0].productId){
              haveId = true;
              this.$notify.error({title: '提示信息',message:'此信息已存在!'});
              break;
           }
        }
        if(!haveId){
          this.productList.push(data.data[0].productId);  //存储物料id
          data.data[0].materialId=data.data[0].productId;
          data.data[0].dealerName="";
          data.data[0].subDealer="";
          data.data[0].ownerCode="";
          data.data[0].contractNum=0;
          data.data[0].factorySinglePrice=0;
          data.data[0].stateSubsidy=0;
          data.data[0].localSubsidy=0;
          data.data[0].discount=0;
          data.data[0].actualSinglePrice=0;
          data.data[0].actualTotalPrice=0;
          this.dataSource.push(Object.assign({},data.data[0]));
          
        }
      }
      
      this.visibleProduct = data.visible; //关闭弹窗
    },
    // 经销商打开窗口 -传数据
    dealerHandle(row) {
      this.editRow = Object.assign({},{"index":row.index});
      this.initDealerData={
        excludeBigCustomer:true,//是否查询大客户经销商，如果查询 true，不查询 false
        id:1001
      }
      this.visibleDealer = true;
    },
    // 经销商关闭窗口 -返回数据
    closeDealer(data) {
      this.dataSource[this.editRow.index].dealerName = data.data[0].dealerName;
      this.dataSource[this.editRow.index].ownerCode = data.data[0].dealerCode;
      this.visibleDealer = data.visible; //关闭弹窗
    },
    //列表删除
    editHandle(row){
      this.dataSource.splice(row.index,1);
      this.productList.splice(row.index,1);
    },
 
    // 出卖人表单数据获取  
    formChangeHandleSeller(data){
      this.formData.seller = data;

      this.$refs.buyerInfo.SUBMIT_FORM();
    },
    // 买受人表单数据获取  
    formChangeHandleBuyer(data){
      this.formData.buyer = data;

      this.$refs.contractInfo.SUBMIT_FORM();
    },
    // 合同信息表单数据获取  
    formChangeHandleContract(data){
      this.formData.contract = data;

      this.$refs.fileInfo.SUBMIT_FORM();
    },
    // 附件信息表单数据获取  
    formChangeHandleFile(data){
      this.formData.file = data;

      this.doSave();
    },
    
    //保存   
    saveDialog(){
      this.$refs.sellerInfo.SUBMIT_FORM();
    },
    async doSave(){
      let fileUrlList = [];
      for (let i = 0; i < this.formData.file.fileUrl.length; i++) {
        fileUrlList.push(this.formData.file.fileUrl[i].url);
      }

      let submitData = Object.assign({},this.formData.seller,this.formData.buyer,this.formData.contract);
      submitData.majorContractDetailDTOList = this.dataSource;
      submitData.urls = fileUrlList;
      // const res = await insertContract(submitData);

      let res;
      //如果传入参数不为空并且为修改
      if(this.value!=null && this.value.type=="edit"){
        res = await updataContract(submitData,this.contractId);
      }else{
        res = await insertContract(submitData);
      }

      if (res.resultCode === 200) {
        this.$notify.success({title: '提示信息',message:'保存成功!'});
        // 重新加载
        this.closeDialog('refresh');
      }else {
        this.$notify.error({title: '提示信息',message:res.errMsg||'保存失败!'});
        this.closeDialog();
      }
    },
    //取消操作
    closeDialog(type) {
      this.$emit('close', { visible: false,type:type});
    }
  }
};
</script>

<style lang="less" scoped>
</style>
